package com.wu.company.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * created by wuyanshen on 2017/12/19 0:04
 */
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private WebSuccessHandler webSuccessHandler;

    @Autowired
    private WebFailHandler webFailHandler;

    @Autowired
    private WebUserDetailService webUserDetailService;

    @Autowired
    private MD5Util md5Util;

    @Autowired
    private Md5 md5;

    /**
     *
     * @EnableWebSecurity: 禁用Boot的默认Security配置，配合@Configuration启用自定义配置（需要扩展WebSecurityConfigurerAdapter）
     * @EnableGlobalMethodSecurity(prePostEnabled = true): 启用Security注解，例如最常用的@PreAuthorize
     * configure(HttpSecurity): Request层面的配置，对应XML Configuration中的<http>元素
     * configure(WebSecurity): Web层面的配置，一般用来配置无需安全检查的路径
     * configure(AuthenticationManagerBuilder): 身份验证配置，用于注入自定义身份验证Bean和密码校验规则
     */

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()
                .loginPage("/login")
                .loginProcessingUrl("/mylogin")
//                .successForwardUrl("/index") //设置了successHandler后这个配置就不生效了
//                .defaultSuccessUrl("/index") //设置了successHandler后这个配置就不生效了
//                .failureUrl("/login/login.jsp?error=yes") //设置了failureHandler后这个配置就不生效了
                .usernameParameter("j_username")
                .passwordParameter("j_password")
                .permitAll()
                .successHandler(webSuccessHandler)//登录成功后可使用loginSuccessHandler()存储用户信息
                .failureHandler(webFailHandler)
                .and()
                .authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .logout().logoutUrl("/logout")
                .logoutSuccessUrl("/login/login.jsp")
                .and()
                .csrf().disable();

    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(webUserDetailService)//指定
        .passwordEncoder(md5);//指定使用md5给密码加密

    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/login/*");
    }
}
